/**
 * 
 */
package com.sapient.service.client;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

import com.sapient.service.QuestionDTO;
import com.sapient.service.ServiceException;
import com.sapient.service.SessionController;
import com.sapient.service.operation.OperationFactory;


public class QuestionServiceClient {
	
	private SessionController sessionController;
	private OperationFactory operationFactory;
	public QuestionServiceClient(SessionController session, OperationFactory operationFactory){
		this.sessionController = session;
		this.operationFactory = operationFactory;
	}

	public int executeTest(final String name) throws ServiceException{
		int count = 0;
		sessionController.establishNewSession(name);
		while(count <10){
			QuestionDTO question = sessionController.nextQuestion();
			int answer = operationFactory.getOperationHandler(question.getOperation()).compute(question.getFirstNumber(), question.getSecondNumber());
			boolean	pass = sessionController.postAnswerAndGetResult(answer);
			if(!pass){
				count = -1;
				sessionController.establishNewSession(name);
			}
			count++;
		}
		return count;
	}
		
	
	
	public static void main(String[] args) throws ServiceException {
        
		QuestionServiceClient test = new QuestionServiceClient(new SessionController(getHttpClient(false)), new OperationFactory());
		System.out.println(test.executeTest("SANGHARSH") == 10 ? "COMPLETED" : "FAILED");
	}

	private static final int proxyServerPort = 8080;
	private static final String proxyServerHost = "eu.proxy.sapient.com";
	private static final String proxyUsername = "sapient/sgaut2";
	private static final String proxyPassword = "password";
	
	private static HttpClient getHttpClient(boolean withProxyEnabled) {
		
		DefaultHttpClient client = new DefaultHttpClient();
		if(withProxyEnabled){		
			HttpHost proxy = new HttpHost(proxyServerHost, proxyServerPort , "http");
	        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	        client.getCredentialsProvider().setCredentials(
	        new AuthScope(proxyServerHost, proxyServerPort),
	        new UsernamePasswordCredentials(proxyUsername, proxyPassword));
		}
        return client;
	}
}
